<template>
<div  id="app22">
  <el-card>
  <el-container>
    <el-aside width="300px">
      <el-card>
        <div slot="header" class="clearfix">
          <span>院系信息</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">全部</el-button> -->
        </div>
        <el-tree icon-class="el-icon-document" ref="depTree" highlight-current default-expand-all :data="treeData" :props="defaultProps2" @node-click="handleNodeClick" :expand-on-click-node="false"></el-tree>
      </el-card>
      <!-- <el-menu class="el-menu-demo" mode="horizontal">
        <el-menu-item :index="index" v-for="(a,index) in areas" :key="index">{{a.area}}</el-menu-item>
      </el-menu> -->
    </el-aside>
    <el-main style="padding: 0">
      <el-card>
        <div class="form">
          <el-form :inline="true">
            <el-form-item label="姓名">
              <el-input v-model="formModel.name" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="formModel.phone" placeholder=""></el-input>
            </el-form-item>
            <!-- <el-form-item label="角色">
               <el-select v-model="formModel.roleId" placeholder="请选择">
              <el-option
                v-for="item in multiSelections.optionss"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="getList">查询</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button>重置</el-button>
            </el-form-item> -->
          </el-form>
        </div>
        <div slot="header">
          <el-button type="primary" size="small" @click="add">新增</el-button>
          <el-button type="danger" size="small" @click="batchDelete">删除</el-button>
        </div>
        <!-- 提示部分 -->
        <!-- <div class="point">
          <div class="point-text">
            <span>
              表格描述
              <el-button type="text">清空</el-button>
            </span>
          </div>
        </div> -->
        <!-- 主体部分的表格 -->
        <el-table stripe :data="tableData.row" style="width: 100%" :current-row-key="tableData.row.id" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column
            type="index"
            label="编号"
            width="50"
          >
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="slotProps">
              {{slotProps.row.name}}
            </template>
          </el-table-column>
          <el-table-column label="电话">
            <template slot-scope="slotProps">
              {{slotProps.row.phone}}
            </template>
          </el-table-column>
          <el-table-column label="邮箱">
            <template slot-scope="slotProps">
              {{slotProps.row.email}}
            </template>
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="slotProps">
              教师
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="slotProps">
              {{slotProps.row.status==0 ? "正常" : ""}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="关联光交箱类型">
            <template slot-scope="slotProps">
              <el-button type="text">5</el-button>
            </template>
          </el-table-column> -->
          <el-table-column label="创建时间" width="200">
            <template slot-scope="slotProps">
              {{slotProps.row.createTime}}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="slotProps">
              <el-button type="text" @click="edit(slotProps.$index)">编辑</el-button>
              <!-- <el-button type="text" @click="del(slotProps.$index)">删除</el-button>
              <el-button type="text" @click="relate(slotProps.$index)">分配设备</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 底部的翻页器 -->
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :pager-count="5"
            :total="page.total"
            :page-size="page.pageSize"
            :current-page="page.currentPage"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-card>
    </el-main>
    <!-- 点击编辑按钮出现的弹框 -->
    <el-dialog
      :title="adedDialog.title"
      :visible.sync="adedDialog.show"
      @close="handleDialogClose(`formData`)"
      width="900px"
      center
    >
      <el-dialog
        width="30%"
        title="选择片区"
        :visible.sync="area.innerVisible"
        append-to-body>
        <el-tree
          highlight-current
          class="filter-tree"
          :data="area.treeData"
          :expand-on-click-node="false"
          node-key="id"
          @node-click="handleAreaClick"
          ref="tree" style="overflow: auto;height: 28rem;">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ data.name }}</span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="area.innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmArea">确 定</el-button>
        </div>
      </el-dialog>
      <el-form ref="formData" :model="formData" :rules="ruleForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="默认位六个1"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="不能重复"></el-input>
        </el-form-item>
       
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="formData.email" placeholder="不能重复"></el-input>
        </el-form-item>

        <!-- <el-form-item label="角色" prop="roles">
             <el-select v-model="formData.roleId" placeholder="请选择">
              <el-option
                v-for="item in multiSelections.optionss"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item> -->
        
     
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="restForm('formData')">重 置</el-button>
        <el-button type="primary" v-show="adedDialog.showButton" @click="editSure(`formData`)">编 辑</el-button>
        <el-button type="primary" v-show="!adedDialog.showButton" @click="addSure(`formData`)">立即添加</el-button>
        <el-button @click="adedDialog.show = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 点击关联设备的时候，弹出的弹框 ，弹框主体内容为设备树 -->
    <el-dialog
      :title="relDialog.title"
      :visible.sync="relDialog.show"
      width="500px"
      center
    >
      <!-- 设备树 -->
      <el-tree icon-class="el-icon-document":data="experimentTreeData" :props="defaultProps" show-checkbox ref="tree" node-key="id"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="relDialog.show = false">取 消</el-button>
        <el-button type="primary" @click="relSure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的管理区域的弹出框 -->
    <!-- <el-dialog
      title="区域管理"
      :visible.sync="districtDialog.dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-tree
        :data="districtDialog.resources"
        :default-expanded-keys="defaultExpandedKeys"
        :props="districtDialog.defaultProps"
        :lazy="lazzy"
        :load="lazyDistrictLoad"
        show-checkbox
        ref="tree"
        node-key="id"
        >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleDialog">取 消</el-button>
        <el-button type="primary" @click="updateRoleResources">保存</el-button>
      </span>
    </el-dialog> -->
  </el-container>
    </el-card>
    </div>
</template>
<script>
import request from '@/utils/request'
import wangeditor from '@/components/wangEditor/index.vue'
import { buildTree } from '@/utils/index'

export default {
  components: {
    wangeditor
  },
  mounted() {
    this.getList()
    request.get('/ac/department').then(res => {
      this.area.treeData = buildTree(res.content)
    })
    this.getTreeList()
    // this.getDeviceList()
  },
  data() {
    return {
      lazzy: true,
      formModel: {
        name: null,
        phone: null
      },
      defaultExpandedKeys: [],
      page: { // 页面相关数据
        total: 10, // 数据总数
        pageSize: 10, // 一页中最多的数据数
        currentPage: 1, // 当前页面
        experimentTotal: 10, // 特殊需求下的数据
        PageExperimentSize: 1000,
        currentExperimentPage: 1
      },
      tableData: {
        row: []
      },
      inputSearch: '',
      delDialog: {
        show: false,
        content: '',
        title: '删除',
        id: ''
      },
      adedDialog: {
        show: false,
        content: '',
        title: '',
        showButton: ''
      },
      relDialog: {
        title: '选择关联的设备类型',
        show: false
      },
      districtDialog: {
        dialogVisible: false,
        defaultProps: {
          label: 'name'
        },
        resources: [],
        defaultSelected: [],
        defaultSelectedDistrict: [],
        parentId: 0
      },
      formData: {
        selectedRole: '',
        selectedDistrictIds: [],
        name: ''
      },
      currentIndex: {
        editIndex: '',
        delIndex: ''
      }, // 当前所操作的数据的下标
      currentLabId: '',
      experimentTreeData: [], // 设备树的值
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      editorData: '',
      editorAll: {},
      options: [{
        value: 0,
        label: '暂未开放'
      }, {
        value: 1,
        label: '开放预约'
      }],
      ruleForm: { // 表单验证
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      radioNumber: 1, // 使用单选框来控制获取光交箱可容纳人数的方式
      dialogTable: {
        deviceData: [], // 设备表格中的数据
        currentRow: '',
        formTableData: [],
        deviceName: ''
      },
      treeData: [],
      defaultProps2: {
        children: 'children',
        label: 'name'
      },
      multipleSelection: [],
      multiSelections: {
        optionss: []
      },
      area: {
        innerVisible: false,
        treeData: [],
        val: {
          code: '',
          name: ''
        }
      }
    }
  },
  methods: {
    handleAreaClick(data) {
      this.area.val = data
    },
    // 点击弹出区域选择框
    areaChoose() {
      this.area.innerVisible = true
    },
    confirmArea() {
      this.formData.district = this.area.val.name
      this.area.innerVisible = false
    },
    // 获取表格选中
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCloseDistrict(item) {
      this.districtDialog.defaultSelectedDistrict.splice(this.districtDialog.defaultSelectedDistrict.indexOf(item), 1)
      this.districtDialog.defaultSelected.splice(this.districtDialog.defaultSelected.indexOf(item.id), 1)
    },
    lazyDistrictLoad(node, resolve) {
      if (node.level === 0) {
        request.get('/common/commonDistrict/' + this.districtDialog.parentId).then(res => {
          return resolve(res.content)
        })
      }
      if (node.level >= 1) {
        request.get('/common/commonDistrict/' + node.key).then(res => {
          return resolve(res.content)
        })
      }
    },
    doDistrictTreeShow(level) {
      this.districtDialog.dialogVisible = true
      if (this.$refs.tree !== undefined && this.$refs.tree !== null) {
        this.$refs.tree.setCheckedKeys([])
        for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
          this.$refs.tree.store._getAllNodes()[i].expanded = this.isexpand
        }
      }
      // this.defaultExpandedKeys = this.districtDialog.defaultSelected
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        this.$refs.tree.setCheckedKeys([])
        done()
      }).catch(_ => {})
    },
    cancleDialog() {
      this.$refs.tree.setCheckedKeys([])
      this.districtDialog.dialogVisible = false
    },
    updateRoleResources() {
      // 要提交formData  管理区域ID数组
      // 获取选择的key
      if (this.districtDialog.defaultSelectedDistrict) {
        this.$refs.tree.getCheckedNodes().forEach((value, index) => {
          var muu = this.districtDialog.defaultSelectedDistrict.find(vaf => vaf.id === value.id)
          if (!muu) {
            this.districtDialog.defaultSelectedDistrict.push(value)
          }
        })
      } else {
        this.districtDialog.defaultSelectedDistrict = this.$refs.tree.getCheckedNodes()
      }
      if (this.districtDialog.defaultSelected) {
        this.$refs.tree.getCheckedKeys().forEach((value, index) => {
          var mu = this.districtDialog.defaultSelected.find(vae => vae === value)
          if (!mu) {
            this.districtDialog.defaultSelected.push(value)
          }
        })
      } else {
        this.districtDialog.defaultSelected = this.$refs.tree.getCheckedKeys()
      }
      this.districtDialog.dialogVisible = false
    },
    // 批量删除
    batchDelete() {
      const t = this.multipleSelection
      var ids = ''
      t.forEach(element => {
        ids = ids === '' ? ids + element.id : ids + ',' + element.id
      })
      request.delete('/ac/userManage/' + ids[0], {
        params: {
          'ids': ids
        }
      }).then(res => {
        if (res.code === 0) {
          this.getList() // 删除后重新加载页面
          this.$notify({
            title: '操作提示',
            message: res.content
          })
        }
      })
      this.getList()
    },
    // 根据id查询光交箱详细信息
    handleNodeClick(data) {
      console.log(data)
      return request.get('/ac/userManage/userList', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage,
        roleId: 1,
        departmentCode: data.code
      }}).then(res => {
        this.tableData.row = res.content.records
        this.page.total = res.content.total
      })
    },
    // 查询光交箱分页信息，获取光交箱列表
    getTreeList() {
      return request.get('/ac/department').then(res => {
        this.treeData = buildTree(res.content)
      })
    },
    getList() {
      const n = this.$refs.depTree.getCurrentNode()
      console.log(this.formModel)
      console.log(n)
      request.get('/ac/role').then(res => {
        this.multiSelections.optionss = res.content
      })
      return request.get('/ac/userManage/userList', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage,
        departmentCode: n === null ? null : n.code,
        roleId: 1,
        ...this.formModel
      }}).then(res => {
        this.tableData.row = res.content.records
        this.page.total = res.content.total
      })
    },
    // 获取所有的设备列表
    getExperimentList() {
      request.get('/labs/experitype/page', { params: {
        size: this.page.PageExperimentSize,
        current: this.page.currentExperimentPage
      }}).then(res => {
        this.experimentTreeData = res.content.records
        this.page.experimentTotal = res.content.total
      })
    },
    // 获取某光交箱下的设备列表的id
    getLabAndExperimentIds() {
      request.get('/labs/experitype/page').then(res => {
        this.hasExperimentIds = []
        for (let i = 0; i < res.content.records.length; i++) {
          this.hasExperimentIds[i] = res.content.records[i].experimentId
        }
      }).then(() => {
        this.$refs.tree.setCheckedKeys(this.hasExperimentIds)
      })
    },
    // 获取弹框中的设备的数据
    getDeviceList() {
      request.get('/items/device', { params: {
        size: 100,
        current: 1,
        name: this.dialogTable.deviceName
      }}).then(res => {
        this.dialogTable.deviceData = res.content.records
      })
    },
    // 删除操作
    del(index) {
      this.currentIndex.delIndex = index
      this.delDialog.content = '您确定删除 ' + this.tableData.row[this.currentIndex.delIndex].name + ' 吗？'
      this.delDialog.id = this.tableData.row[this.currentIndex.delIndex].id
      this.delDialog.show = true
    },
    delSure() {
      this.delDialog.show = false
      request.delete(`/items/lab/${this.delDialog.id}`).then(res => {
        if (res.code === 0) {
          this.getList() // 删除后重新加载页面
        }
      })
    },
    // 编辑操作
    edit(index) {
      request.get('/ac/userManage/' + this.tableData.row[index]['id']).then(res => {
        this.formData = res.content
        // this.formData.id = this.tableData.row[index]['id']
        // this.formData.name = res.content.name
        // this.formData.password = res.content.password
        // this.formData.phone = res.content.phone
        // this.formData.email = res.content.email
        // // this.formData = res.content
        // this.multiSelections.optionss = res.content.roles
        // this.formData.selectedRole = res.content.selectRole.id
        // this.multiSelections.districts = res.content.districts
      })
      // request.get('/common/commonDistrict/user/id?id=' + this.tableData.row[index]['id']).then(res => {
      //   this.districtDialog.defaultSelectedDistrict = []
      //   this.districtDialog.defaultSelected = []
      //   this.districtDialog.defaultSelectedDistrict = res.content
      //   if (this.districtDialog.defaultSelectedDistrict !== null) {
      //     this.districtDialog.defaultSelectedDistrict.forEach((value, index) => {
      //       this.districtDialog.defaultSelected.push(value.id)
      //     })
      //   }
      // })
      this.adedDialog.title = '编辑'
      this.adedDialog.show = true
      this.adedDialog.showButton = true
    },
    editSure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.formData.selectedDistrictIds = []
          this.formData.selectedDistrictIds = this.districtDialog.defaultSelected
          request.put('/user/userRole/role/districts', { ...this.formData }).then(res => {
            this.clearSelectedData()
            this.adedDialog.show = false
          })
        }
      })
    },
    // 关联设备操作
    relate(index) {
      this.currentLabId = this.tableData.row[index].id
      this.relDialog.show = true
      this.getLabAndExperimentIds()
    },
    relSure() {
      request.post(`/items/labAndExperiment/bylab/${this.currentLabId}`,
        this.$refs.tree.getCheckedKeys()
      ).then(res => {
        this.$message.success(res.content)
        this.$refs.tree.setCheckedKeys([])
        this.relDialog.show = false
      })
    },
    // 添加操作
    add() {
      if (this.$refs.depTree.getCurrentNode() == null) {
        alert('先选择院系')
        return
      }
      request.get('/ac/role').then(res => {
        this.multiSelections.optionss = res.content
        this.formData.selectedRole = res.content[1]['id']
      })

      this.formData = {} // 富文本编辑器的重置有问题
      this.districtDialog.defaultSelectedDistrict = []
      this.adedDialog.title = '添加'
      this.adedDialog.show = true
      this.adedDialog.showButton = false
    },
    addSure(formName) { //  经过通信，formData与表单中的数据绑定
      this.$refs[formName].validate(valid => {
        if (valid) {
          const n = this.$refs.depTree.getCurrentNode()
          this.formData.departmentCode = n.code
          this.formData.departmentId = n.id
          this.formData.selectedDistrictIds = []
          this.formData.selectedDistrictIds = this.districtDialog.defaultSelected
          request.post('/user/userRole/role/districts', { ...this.formData }).then(res => {
            this.clearSelectedData()
            this.getList()
            this.adedDialog.show = false
            console.log(res)
          })
        }
      })
    },
    clearSelectedData() {
      this.formData.selectedDistrictIds = []
      this.districtDialog.defaultSelectedDistrict = []
      this.formData.selectedRole = ''
      this.districtDialog.defaultSelected = []
      this.formData.selectedDistrictIds = []
      this.formData.departmentCode = ''
      this.formData.departmentId = ''
    },
    // 单选表格中的数据
    handleTableCurrentChange(obj) {
      // this.dialogTable.formTableData[0] = { ...obj } // 由于js本身的限制，vue不能检测该方式变动的数组
      this.dialogTable.formTableData.splice(0, 1, { ...obj })
    },
    // 翻页时触发该函数
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 关闭弹窗时会触发该钩子，重置表单
    handleDialogClose(formName) {
      this.adedDialog.show = false
      this.dialogTable.formTableData = []
      this.dialogTable.deviceName = ''
      this.radioNumber = 1
      this.restForm(formName)
      this.clearSelectedData()
    },
    // 重置表单函数
    restForm(formName) {
      this.$refs[formName].resetFields() // 重置
      // this.formData = {} // 将表单置空
    },
    // 搜索设备
    searchDevice() {
      // this.getDeviceList()
    }
  }
}
</script>

<style scoped>
.point {
  width: 100%;
  height: 40px;
  margin-top: 8px;
  background-color: #e6f7f7;
  border: 1px solid rgba(186, 231, 255, 1);
  border-radius: 4px;
  box-shadow: none;
  font-size: 14px;
  text-align: left;
}
.point-text {
  margin-left: 14px;
  line-height: 40px;
}
.pagination {
  float: right;
  margin-bottom: 15px;
}
.tag-class{
  margin: 3px;
}
</style>
